package com.lzc.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzc.blog.admin.mapper.SysUserMapper;
import com.lzc.blog.admin.model.params.PageParam;
import com.lzc.blog.admin.pojo.SysUser;
import com.lzc.blog.admin.service.SysUserService;
import com.lzc.blog.admin.utils.TimeUtil;
import com.lzc.blog.admin.vo.PageResult;
import com.lzc.blog.admin.vo.Result;
import com.lzc.blog.admin.vo.SysUserVo;
import com.mysql.cj.util.StringUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @SneakyThrows
    @Override
    public Result sysUserList(PageParam pageParam) {

        IPage<SysUser> page=new Page(pageParam.getCurrentPage(),pageParam.getPageSize());
        LambdaQueryWrapper<SysUser> queryWrapper=new LambdaQueryWrapper<>();
        if (!StringUtils.isEmptyOrWhitespaceOnly(pageParam.getQueryString())){
            // and name=?
            queryWrapper.like(SysUser::getAccount,pageParam.getQueryString());
        }
        sysUserMapper.selectPage(page,queryWrapper);
        List<SysUser> sysUserList = page.getRecords();
        List<SysUserVo> sysUserVoList=new ArrayList<>();
        for (SysUser user : sysUserList) {
            SysUserVo userVo=new SysUserVo();
            userVo.setAccount(user.getAccount());
            userVo.setNickName(user.getNickName());
            userVo.setId(user.getId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(new Date(user.getLastLogin()));
            userVo.setLastLogin(format);
            sysUserVoList.add(userVo);
        }

        long total = page.getTotal();
        PageResult<SysUserVo> sysUserPageResult = new PageResult<SysUserVo>(sysUserVoList, total);
        return Result.success(sysUserPageResult);
    }

    @Override
    @Transactional
    public Result delete(String id) {
         sysUserMapper.deleteById(id);
         return Result.success(null);
    }

    @Override
    @Transactional
    public Result updateById(SysUser user) {
        sysUserMapper.updateById(user);
        return Result.success(null);
    }

    @Override
    public SysUser selectById(String id) {
        SysUser user = sysUserMapper.selectById(id);
        return user;
    }
}
